﻿using CommonServiceLocator;
using GalaSoft.MvvmLight.CommandWpf;
using HuiZe.education.Common;
using HuiZe.education.Model;
using HuiZe.education.View;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Navigation;

namespace HuiZe.education.ViewModel
{
    public class LoginViewModel : ViewModelBase
    {
        public LoginView LoginView { get; set; }
        public AccountLoginView AccountView { get; set; }
        private int otherLoginId { get; set; }
        private int otherLoginTpye { get; set; }
        public FrameworkElement LoginViewContent { get; set; }
        public RelayCommand LoginCommand { get { return new RelayCommand(DoLogin); } }
        public RelayCommand<object> FogotPasswordCommand { get { return new RelayCommand<object>(FogotPassword); } } //忘记密码
        public RelayCommand<object> OtherLoginCommand2 { get { return new RelayCommand<object>(OtherLogin); } } //忘记密码
        public RelayCommand<object> OtherLoginCommand { get; set; } //其他登录方式
        //public RelayCommand<object> QQLoginCommand { get; set; } //qq登录
        public RelayCommand<object> WeixinLoginCommand { get; set; } //微信登录
        public RelayCommand OpenOfflinePackageCommand { get; set; } //打开离线课包
        public string strSendValidationCode { get; set; } = "获取验证码";
        public LoginModel LoginModel { get; set; } = new LoginModel();
        public ResetpwdModel ResetpwdModel { get; set; } = new ResetpwdModel();
        public string FirstPwd { get; set; }
        public string SecondPwd { get; set; }
        public bool RemberPwd { get; set; } //记住密码
        public ErrorMsgModel ErrorMsg { get; set; } = new ErrorMsgModel();
        private int timerCount = 60;
        public LoginViewModel()
        {
            if (IsInDesignMode)
            {
                strSendValidationCode = "获取验证码";
            }
            IniCommand();
        }

        private void IniCommand()
        {
            OtherLoginCommand = new RelayCommand<object>(OtherLogin);
            //QQLoginCommand = new RelayCommand<object>(QQLogin);
            WeixinLoginCommand = new RelayCommand<object>(WeixinLogin);
            OpenOfflinePackageCommand = new RelayCommand(OpenOfflinePackage);
        }

        //账户密码登录
        private void DoLogin()
        {
            if (string.IsNullOrEmpty(LoginModel.LoginName))
            {
                ErrorMsg.LoginMobileError = "手机号不能为空";
                return;
            }
            LoginIn();
        }

        //微信登录
        private void WeixinLogin(object obj)
        {

        }

        //qq登录


        //其他方式登录
        //private void OtherLogin(object obj)
        //{

        //}

        //找回密码
        private void FogotPassword(object obj)
        {
            if (obj.ToString() == "1")
            {
                ResetpwdModel.mobile = LoginModel.LoginName;
                NavChanged("ForgotPwdView");
            }

            else if (obj.ToString() == "2") //切换登录
            {
                NavChanged("AccountLoginView");
            }

            else if (obj.ToString() == "3") //发送验证码
            {
                if (timerCount < 60) return;
                if (string.IsNullOrEmpty(ResetpwdModel.mobile))
                {
                    ErrorMsg.ForgotMobileError = "手机号不能为空";
                    return;
                }
                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
                keyValuePairs["mobile"] = ResetpwdModel.mobile;
                keyValuePairs["event"] = "resetpwd";
                string data = JsonHelper.ToJson(keyValuePairs);
                var res = WebApiHelper.HttpPost("/api/sms/send", data);
                if (res.Item1)
                {
                    var request = JsonHelper.FromJson<RequestModel<ReqLoginModel>>(res.Item2);
                    if (request.code != 1)
                    {
                        ErrorMsg.ForgotValidationCodeError = request.msg;
                        return;
                    }
                    Timer timer = new Timer()
                    {
                        Interval = 1000,
                    };
                    timer.Tick += Timer_Tick;
                    timer.Enabled = true;
                    timer.Start();
                }
                else
                {
                    ShowDialogView("验证码发送失败！");
                    return;
                }
            }

            else if (obj.ToString() == "4")//修改并登录
            {
                if (string.IsNullOrEmpty(ResetpwdModel.mobile))
                {
                    ErrorMsg.ForgotMobileError = "手机号不能为空";
                    return;
                }
                if (string.IsNullOrEmpty(ResetpwdModel.captcha))
                {
                    ErrorMsg.ForgotValidationCodeError = "验证码不能为空";
                    return;
                }
                if (string.IsNullOrEmpty(FirstPwd))
                {
                    ErrorMsg.ForgotPwdError = "密码不能为空";
                    return;
                }
                if (string.IsNullOrEmpty(SecondPwd))
                {
                    ErrorMsg.ForgotSecondPwdError = "请输入确认密码";
                    return;
                }
                if (FirstPwd.Length < 6)
                {
                    ErrorMsg.ForgotPwdError = "密码至少6个字符";
                    return;
                }
                //if (SecondPwd.Length < 6)
                //{
                //    ErrorMsg.ForgotSecondPwdError = "确认密码至少6个字符";
                //    return;
                //}
                if (FirstPwd != SecondPwd)
                {
                    ErrorMsg.ForgotSecondPwdError = "两次密码输入不一致";
                    return;
                }
                ResetpwdModel.newpassword = FirstPwd;
                ResetpwdModel.type = "mobile";
                string data = JsonHelper.ToJson(ResetpwdModel);
                var res = WebApiHelper.HttpPost("/api/user/resetpwd", data);
                if (res.Item1)
                {
                    var request = JsonHelper.FromJson<RequestModel<ReqLoginModel>>(res.Item2);
                    if (request.code == 1) //修改成功 直接登陆
                    {
                        LoginModel.LoginName = ResetpwdModel.mobile;
                        LoginModel.LoginPassWord = ResetpwdModel.newpassword;
                        LoginIn();
                    }
                    else
                    {
                        ErrorMsg.ForgotSecondPwdError = request.msg;
                        return;
                    }
                }
                else
                {
                    ShowDialogView("重置密码失败！");
                    return;
                }
            }
        }

        //找回密码
        private void OtherLogin(object obj)
        {
            if (obj.ToString() == "1")
            {
                ResetpwdModel.mobile = LoginModel.LoginName;
                NavChanged("ForgotPwdView");
            }

            else if (obj.ToString() == "2") //切换登录
            {
                NavChanged("AccountLoginView");
            }

            else if (obj.ToString() == "3") //发送验证码
            {
                if (timerCount < 60) return;
                if (string.IsNullOrEmpty(ResetpwdModel.mobile))
                {
                    ErrorMsg.ForgotMobileError = "手机号不能为空";
                    return;
                }
                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
                keyValuePairs["mobile"] = ResetpwdModel.mobile;
                keyValuePairs["event"] = "resetpwd";
                string data = JsonHelper.ToJson(keyValuePairs);
                var res = WebApiHelper.HttpPost("/api/sms/send", data);
                if (res.Item1)
                {
                    var request = JsonHelper.FromJson<RequestModel<ReqLoginModel>>(res.Item2);
                    if (request.code != 1)
                    {
                        ErrorMsg.ForgotValidationCodeError = request.msg;
                        return;
                    }
                    Timer timer = new Timer()
                    {
                        Interval = 1000,
                    };
                    timer.Tick += Timer_Tick;
                    timer.Enabled = true;
                    timer.Start();
                }
                else
                {
                    ShowDialogView("验证码发送失败！");
                    return;
                }
            }

            else if (obj.ToString() == "4")//修改并登录
            {
                if (string.IsNullOrEmpty(ResetpwdModel.mobile))
                {
                    ErrorMsg.ForgotMobileError = "手机号不能为空";
                    return;
                }
                if (string.IsNullOrEmpty(ResetpwdModel.captcha))
                {
                    ErrorMsg.ForgotValidationCodeError = "验证码不能为空";
                    return;
                }
                if (string.IsNullOrEmpty(FirstPwd))
                {
                    ErrorMsg.ForgotPwdError = "密码不能为空";
                    return;
                }
                if (string.IsNullOrEmpty(SecondPwd))
                {
                    ErrorMsg.ForgotSecondPwdError = "请输入确认密码";
                    return;
                }
                if (FirstPwd.Length < 6)
                {
                    ErrorMsg.ForgotPwdError = "密码至少6个字符";
                    return;
                }
                //if (SecondPwd.Length < 6)
                //{
                //    ErrorMsg.ForgotSecondPwdError = "确认密码至少6个字符";
                //    return;
                //}
                if (FirstPwd != SecondPwd)
                {
                    ErrorMsg.ForgotSecondPwdError = "两次密码输入不一致";
                    return;
                }
                ResetpwdModel.newpassword = FirstPwd;
                ResetpwdModel.type = "mobile";
                string data = JsonHelper.ToJson(ResetpwdModel);
                var res = WebApiHelper.HttpPost("/api/user/resetpwd", data);
                if (res.Item1)
                {
                    var request = JsonHelper.FromJson<RequestModel<ReqLoginModel>>(res.Item2);
                    if (request.code == 1) //修改成功 直接登陆
                    {
                        LoginModel.LoginName = ResetpwdModel.mobile;
                        LoginModel.LoginPassWord = ResetpwdModel.newpassword;
                        LoginIn();
                    }
                    else
                    {
                        ErrorMsg.ForgotSecondPwdError = request.msg;
                        return;
                    }
                }
                else
                {
                    ShowDialogView("重置密码失败！");
                    return;
                }
            }

            else if (obj.ToString() == "5")
            {
                if (string.IsNullOrEmpty(ResetpwdModel.mobile))
                {
                    ErrorMsg.ForgotMobileError = "手机号不能为空";
                    return;
                }
                if (string.IsNullOrEmpty(ResetpwdModel.captcha))
                {
                    ErrorMsg.ForgotValidationCodeError = "验证码不能为空";
                    return;
                }
                if (otherLoginTpye == 1)
                    OtherBind(otherLoginId, ResetpwdModel.captcha, ResetpwdModel.mobile, "", "qq");
                else
                    OtherBind(otherLoginId, ResetpwdModel.captcha, ResetpwdModel.mobile, "", "wx");

            }
        }
        private void Timer_Tick(object sender, System.EventArgs e)
        {
            if (timerCount == 0)
            {
                strSendValidationCode = "获取验证码";
            }
            else
            {
                timerCount--;
                strSendValidationCode = $"{timerCount}s";
            }
        }

        //打开离线课包
        private void OpenOfflinePackage()
        {

        }

        public new void NavChanged(string viewName)
        {
            if (!contents.ContainsKey(viewName))
                LoginViewContent = GetFrameworkElement(viewName);
            else
                LoginViewContent = contents[viewName];
        }

        private void LoginIn()
        {
            string data = JsonHelper.ToJson(LoginModel);
            var result = Request<ReqLoginModel>("/api/user/login", data, "登陆");
            if (result.Item1)
            {
                LoginView.Hide();

                HuiZeeducation.Instance.UserInfo = result.Item2.data.userInfo;
                GetLoginLogo();
                Debug.WriteLine($"登陆成功token：{result.Item2.data.userInfo.token}");
                HuiZeeducation.Instance.DownLoadData();
                HuiZeeducation.Instance.UserInfo.userName = LoginModel.LoginName;
                HuiZeeducation.Instance.UserInfo.userPwd = LoginModel.LoginPassWord;


            }
            else
            {
                if (result.Item2 != null)
                    ShowDialogView(result.Item2.msg);
            }
        }

        public void ReqMessage()
        {
            //Dictionary<string, int> keyValuePairs = new Dictionary<string, int>();
            //keyValuePairs["limit"] = limit;
            //keyValuePairs["page"] = CurrentIndex;

            ReqPersonMessageModel msg = new ReqPersonMessageModel
            {
                limit = 15,
                page = 1,
                token = HuiZeeducation.Instance.UserInfo.token,

            };


            var result = Request<ReqMessageModel>("/api/message/index", JsonHelper.ToJson(msg), "消息");
            if (result.Item1)
            {
                //pageCount = result.Item2.data.last_page;

            }

        }
        private void GetLoginLogo()
        {
            ReqLoginUrl model = new ReqLoginUrl
            {

                token = HuiZeeducation.Instance.UserInfo.token,
            };
            string data = JsonHelper.ToJson(model);
            var result = Request<ReqLoginLogo>("/api/user/getLogo", data, "getLogo");
            if (result.Item1)
            {
                HuiZeeducation.Instance.LogoUrl = result.Item2.data.image;
                HuiZeeducation.Instance.UserInfo.logoUrl = result.Item2.data.image;
                //UserInfo = HuiZeeducation.Instance.UserInfo;
            }
            else
            {
                if (result.Item2 != null)
                    ShowDialogView(result.Item2.msg);
            }
        }


        string qqappid = CommonMethods.GetAppConfigValue("QQAPPID").ToString();
        string qqappKey = CommonMethods.GetAppConfigValue("QQAPPKey").ToString();



        public RelayCommand<object> WXLoginCommand
        {
            get
            {
                return new RelayCommand<object>(new Action<object>((o) =>
                {
                    WXLogin();
                }));
            }
        }
        WebBrowser webBrowser = null;
        public string qrcodeUrl { get; set; }



        void WebBrowserMain_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            SetWebBrowserSilent(sender as WebBrowser, true);
        }

        /// <summary>
        /// 设置浏览器静默，不弹错误提示框
        /// </summary>
        /// <param name="webBrowser">要设置的WebBrowser控件浏览器</param>
        /// <param name="silent">是否静默</param>
        private void SetWebBrowserSilent(WebBrowser webBrowser, bool silent)
        {
            FieldInfo fi = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
            if (fi != null)
            {
                object browser = fi.GetValue(webBrowser);
                if (browser != null)
                    browser.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, browser, new object[] { silent });
            }
        }
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

            try
            {
                foreach (HtmlElement he in webBrowser.Document.GetElementsByTagName("img"))
                {
                    string str = he.GetAttribute("className");
                    if (str == "qrcode lightBorder")
                    {
                        qrcodeUrl = he.GetAttribute("src"); //获取微信生成的二维码图片,那个网页中只有两个图片,且二维码是第二张图片.
                        LoginView.ShowImg(qrcodeUrl);
                    }
                }
            }
            catch { }



        }

        public void WXLogin()
        {
            //webBrowser = new WebBrowser();
            //webBrowser.DocumentCompleted += webBrowser1_DocumentCompleted;
            //webBrowser.Navigating += new WebBrowserNavigatingEventHandler(webBrowser1_Navigating);
            //string state = GetStateCode();
            //string url2 = "https://d-zhzh.bigchun.com/#/otherLogin?type=wx";
            //string wxAPPID = CommonMethods.GetAppConfigValue("WXAPPID").ToString();
            //string wxAppSecret = CommonMethods.GetAppConfigValue("WXAppSecret").ToString();
            //string url = "https://open.weixin.qq.com/connect/qrconnect?appid="+ wxAPPID + "&redirect_uri="+ Uri.EscapeDataString(url2) +"&response_type=code&scope=snsapi_login&state="+ state + "#wechat_redirect";
            //webBrowser.Navigate(url);
            string url = WXLoginUrl(2);
            //string newurl = url;
            //int index = url.IndexOf("d-zhzh.bigchun.com");
            //string preurl = url.Substring(0, index);
            //string nexturl = url.Substring(index+18, url.Length- index-18);
            //newurl = preurl + "admin.jiaodehuiyun.com" + nexturl;

            AccountView.ShowImg(url);
        }

        public void QQLogin()
        {

            //string QQAPPID = CommonMethods.GetAppConfigValue("QQAPPID").ToString();
            //string state = GetStateCode();
            //string url2 = "https://d-zhzh.bigchun.com/#/otherLogin?type=qq";
            //string url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id="+ QQAPPID + "&redirect_uri="+ Uri.EscapeDataString(url2) + "&state="+ state + "";
            string url = QQLoginUrl(2);
            AccountView.ShowQQImg(url);

        }

        public void OtherLogin(string code, string type)
        {
            ReqOtherLoginModel model = new ReqOtherLoginModel
            {
                platform = type,
                code = code,
            };
            string data = JsonHelper.ToJson(model);
            var result = Request<ReqLoginModel>("/api/user/third", data, "第三方登陆");
            if (result.Item1)
            {
                LoginView.Hide();
                HuiZeeducation.Instance.UserInfo = result.Item2.data.userInfo;
                Debug.WriteLine($"登陆成功token：{result.Item2.data.userInfo.token}");
                HuiZeeducation.Instance.DownLoadData();
            }
            else
            {
                if (result.Item2 != null)
                    ShowDialogView(result.Item2.msg);
            }

        }

        protected string GetStateCode()
        {
            Random rand = new Random();
            string data = DateTime.Now.ToString("yyyyMMddHHmmssffff") + rand.Next(1, 0xf423f).ToString();

            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

            byte[] md5byte = md5.ComputeHash(UTF8Encoding.Default.GetBytes(data));

            return BitConverter.ToString(md5byte).Replace("-", "");

        }

        /// <summary>
        /// PC扫码QQ登录地址
        /// </summary>
        /// <param name="Type"></param>
        public string QQLoginUrl(int Type)
        {
            ReqLoginUrl model = new ReqLoginUrl
            {

                type = Type,
            };
            string data = JsonHelper.ToJson(model);
            var result = Request2<ResLoginUrl>("/api/user/pc_qq_login_url", data, "第三方登陆");
            if (result.Item1)
            {
                return result.Item2.data;
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// PC扫码WX登录地址
        /// </summary>
        /// <param name="Type"></param>
        public string WXLoginUrl(int Type)
        {
            ReqLoginUrl model = new ReqLoginUrl
            {

                type = Type,
            };
            string data = JsonHelper.ToJson(model);
            var result = Request2<ResLoginUrl>("/api/user/pc_third_login_url", data, "第三方登陆");
            if (result.Item1)
            {
                return result.Item2.data;
            }
            else
            {
                return null;
            }
        }



        /// <summary>
        /// PC扫码QQ登录
        /// </summary>
        /// <param name="Type"></param>
        public void QQLogin(string Code, string State)
        {
            ReqOtherLogin model = new ReqOtherLogin
            {
                code = Code,
                state = State,
            };
            third_loginCode = Code;
            third_loginState = State;
            string data = JsonHelper.ToJson(model);
            var result = Request3<ResLoginDeatail>("/api/user/pc_qq_login", data, "第三方登陆");
            if (result.Item1)
            {
                LoginView.Hide();
                HuiZeeducation.Instance.UserInfo = result.Item2.data.userinfo;
                GetLoginLogo();
                Debug.WriteLine($"登陆成功token：{result.Item2.data.userinfo.token}");
                HuiZeeducation.Instance.DownLoadData();

            }
            else
            {
                var result2 = resLoginDeatail;
                otherLoginId = result2.data;
                otherLoginTpye = 1;
                if (otherLoginId != 0)
                    NavChanged("OtherLoginView");
            }
        }
        private string third_loginCode { get; set; }
        private string third_loginState { get; set; }

        /// <summary>
        /// PC扫码WX登录
        /// </summary>
        /// <param name="Type"></param>
        public void WXLogin(string Code, string State)
        {
            ReqOtherLogin model = new ReqOtherLogin
            {
                code = Code,
                state = State,
            };
            third_loginCode = Code;
            third_loginState = State;
            string data = JsonHelper.ToJson(model);
            var result = Request3<ResLoginDeatail>("/api/user/pc_third_login", data, "第三方登陆");
            if (result.Item1)
            {
                LoginView.Hide();
                HuiZeeducation.Instance.UserInfo = result.Item2.data.userinfo;
                GetLoginLogo();
                Debug.WriteLine($"登陆成功token：{result.Item2.data.userinfo.token}");
                HuiZeeducation.Instance.DownLoadData();
            }
            else
            {
                var result2 = resLoginDeatail;
                otherLoginId = result2.data;
                otherLoginTpye = 2;
                if (otherLoginId != 0)
                    NavChanged("OtherLoginView");

            }
        }


        /// <summary>
        /// PC扫码WX登录
        /// </summary>
        /// <param name="Type"></param>
        public void OtherBind(int Id, string Code, string phone, string State, string bindType)
        {
            BindModel relieveModel = new BindModel
            {
                id = Id,
                mobile = phone,
                code = Code,

                type = bindType,
            };

            string data = JsonHelper.ToJson(relieveModel);
            var res = WebApiHelper.HttpPost("/api/user/binging", data);
            if (res.Item1)
            {
                //var result = Request<Userinfo>("/api/user/getuser", data, "获取登录用户信息");
                var request = JsonHelper.FromJson<RequestModel<Userinfo>>(res.Item2);
                if (request.code == 1) //修改成功 直接登陆
                {

                    LoginView.Hide();
                    HuiZeeducation.Instance.UserInfo = request.data;
                    GetLoginLogo();
                    Debug.WriteLine($"登陆成功token：{ request.data.token}");
                    HuiZeeducation.Instance.DownLoadData();
                    GetLoginInfo();
                    //HuiZeeducation.Instance.UserInfo.userName = LoginModel.LoginName;
                    //HuiZeeducation.Instance.UserInfo.userPwd = LoginModel.LoginPassWord;

                    //if (otherLoginTpye==1)
                    //{
                    //QQLogin(third_loginCode, third_loginState);
                    //NavChanged("AccountLoginView");
                    //string url = QQLoginUrl(2);
                    //third_loginCode = Code;
                    //third_loginState = State;

                    //ShowQQLogin showQQLogin = new ShowQQLogin();
                    //showQQLogin.LoadType = 1;
                    //showQQLogin.loadUrl = url;
                    //showQQLogin.DataContext = this;
                    //showQQLogin.ShowDialog();
                    //}
                    //else 
                    //{
                    //WXLogin(third_loginCode, third_loginState);
                    //NavChanged("AccountLoginView");
                    //string url = WXLoginUrl(2);
                    //ShowQQLogin showQQLogin = new ShowQQLogin();
                    //showQQLogin.LoadType = 2;
                    //showQQLogin.loadUrl = url;
                    //showQQLogin.DataContext = this;
                    //showQQLogin.ShowDialog();
                    //}
                }
                else
                {
                    ShowDialogView(request.msg);
                    ErrorMsg.ForgotSecondPwdError = request.msg;
                    return;
                }
            }
            else
            {
                ShowDialogView("绑定失败！");
                return;
            }
        }

        public void GetLoginInfo()
        {

            ReqLoginUrl model = new ReqLoginUrl
            {
                token = HuiZeeducation.Instance.UserInfo.token,
            };
            string data = JsonHelper.ToJson(model);
            var result = Request<Userinfo>("/api/user/getuser", data, "获取登录用户信息");
            if (result.Item1)
            {


                string token = HuiZeeducation.Instance.UserInfo.token;
                string expireTime = HuiZeeducation.Instance.UserInfo.expiretime2;
                HuiZeeducation.Instance.UserInfo = result.Item2.data;

                HuiZeeducation.Instance.UserInfo.token = token;

                HuiZeeducation.Instance.UserInfo.expiretime2 = expireTime;



            }
            else
            {

            }






        }
    }
}
